const axios = require('axios')
import Vue from "vue";
import router from '../router';
import ElementUI from 'element-ui';
import {storage} from '@/utils';
let load;
// Vue.use(ToastPlugin)

const instance = axios.create({
    baseURL: '',
    timeout: 60000,
    responseType: 'json',
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    }
})

// 请求拦截器
instance.interceptors.request.use(
    config => {
        load = ElementUI.Loading.service({ fullscreen: true })
        let loginInfo = storage.get('loginInfo') || '';
        config.headers['token'] = loginInfo.token;
        config.baseURL = $conf.baseURL;
        if(config.url === '/pc/login'){
            config.headers['token'] = ''
        }
        return config;
    },
    error => {
        // Vue.$vux.toast.text('请求出错')
        return Promise.reject(error);
    })

// 响应拦截器
instance.interceptors.response.use(
    response => {
        load.close();
        let result = response.data;
        if (result.code == 200) {
            return result.data;
        } else {
            if(result.code == 204) {
                router.push('/login');
            } else {
                ElementUI.Message({
                    title: '错误',
                    message: result.msg,
                    type: 'error'
                })
            }
            // Vue.$vux.toast.text(response.msg || '系统错误')
            return Promise.reject(response)
        }
}, error => {
    // Vue.$vux.toast.text(error.message || '请求失败')
    ElementUI.Notification({
        title: '错误',
        message: error.message,
        type: 'error'
    })
    return Promise.reject(error);
})

export default instance
